﻿using CK.Sprite.CrossCutting;
using CK.Sprite.ThirdContract.Model;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json;
using CK.Sprite.Framework;
using Microsoft.Extensions.Logging;

namespace CK.Sprite.ThirdContract
{
    public class MessageSendService : IMessageSendService
    {
        private readonly SpriteConfig _spriteConfig;
        protected ILogger<MessageSendService> Logger;

        public MessageSendService(IOptions<SpriteConfig> spriteConfigOption, ILogger<MessageSendService> logger)
        {
            _spriteConfig = spriteConfigOption.Value;
            Logger = logger;
        }

        public async Task<string> AddMessageSend(CreateMessageSendDto createMessageSendDto)
        {
#if DEBUG
            return "";
#endif
            try
            {
                using (var client = new HttpClient())
                {
                    var url = _spriteConfig.MessageUrl + "api/messagecenter/MessageSend/AddMessageSendAsync";

                    var response = await client.PostAsync(
                        url,
                        new StringContent(
                            JsonConvert.SerializeObject(createMessageSendDto),
                            Encoding.UTF8,
                            "application/json"
                        )
                    );

                    if (response.IsSuccessStatusCode)
                    {
                        var responseContent = await response.Content.ReadAsStringAsync();
                        return responseContent;
                    }
                    else
                    {
                        throw new SpriteException("消息添加失败");
                    }
                }
            }
            catch(Exception ex)
            {
                Logger.LogWarning($"发送消息失败" + ex.Message);
                return "";
            }
        }
    }
}
